
class File():
    """实现__enter__和__exit__方法的类可用with"""

    def __init__(self,filename,mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        print("enter!!!")
        self.f = open(self.filename,self.mode)
        return self.f

    def __exit__(self, *args):
        print("exit!!!")
        self.f.close()

from contextlib import contextmanager

@contextmanager
def my_open(file,mode):
    """使用contextmanager注解的方法可以使用with"""
    f = open(file,mode)
    yield f
    f.close()

with File("000.txt","w") as f :
    print("writing")
    f.write("pypypy")

with my_open("000.txt","a") as f :
    print("writing")
    f.write("pypypy")
